package formin.powerbar.core;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import formin.powerbar.data.*;



public class PowerBarFileIO {
	private Properties properties;
	private SettingsData settingsData;
	private FileInputStream fis;
	private FileOutputStream fos;
	
	
	public PowerBarFileIO(){
		settingsData = new SettingsData();
		
	}
	
	public SettingsData readSettings(){
		properties = new Properties();
		try {
            fis = new FileInputStream("settings.xml");          
            properties.loadFromXML(fis);

            settingsData.setNumberPlugs(Integer.parseInt(properties.getProperty(Constants.SETTINGS_FILE_STRING_NUMBER_PLUGS)));
            
            fis.close();
            
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
        	fis = null;
        }
        return settingsData;
	}

	public void writeSettings(){
		properties = new Properties();
		properties.setProperty(Constants.SETTINGS_FILE_STRING_NUMBER_PLUGS, String.valueOf(settingsData.getNumbPlugs()));
		properties.setProperty(Constants.SETTINGS_FILE_STRING_NUMBER_SENSORS, String.valueOf(settingsData.getNumbSensors()));
		try{
			fos = new FileOutputStream("settings.xml");
			properties.storeToXML(fos, "Formin PowerBar Settings File", "UTF-8");
			fos.close();
		}catch(IOException e){
			System.out.println(e.getMessage());
		}finally{
			fos = null;
		}
	}
	
	public PlugCollection readPlugData (int numberPlugs){
		PlugCollection plugs = new PlugCollection(numberPlugs);
		properties = new Properties();
		String temp = "";
		try{
			fis = new FileInputStream("plugdata.xml");
			properties.loadFromXML(fis);
			
			//loop thru xml to plugdata elements
			for(int i = 0; i < numberPlugs; i++){
				plugs.getPlug(i).setStatusFromString(properties.getProperty(Constants.PLUG_DATAFILE_PROPERTY_ON_OFF_STRING+String.valueOf(i)));
			}
			
			fis.close();
			
		}catch(IOException e){
			System.out.println(e.getMessage());
		}finally{
			fis = null;
		}
		return plugs;
	}
	
	public void writePlugData(PlugCollection plugs){
		properties = new Properties();
		for(int i = 0; i < plugs.getLength(); i++){
			properties.setProperty(Constants.PLUG_DATAFILE_PROPERTY_ON_OFF_STRING+String.valueOf(i), plugs.getPlug(i).getPlugString());
			properties.setProperty(Constants.PLUG_DATAFILE_PROPERTY_TYPE + String.valueOf(i), plugs.getPlug(i).getPlugType());
		}
		
		try{
			fos = new FileOutputStream ("plugdata.xml");
			properties.storeToXML(fos, "Formin PowerBar Plug Data File", "UTF-8");
			fos.close();
		}catch (IOException e){
			System.out.println(e.getMessage());
		}finally{
			fos = null;
		}
	}
}
